﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Documents
//  File name:	LookupFieldWithPickerEntityEditor.cs
//  Developer:	Solomatov Igor
//  Created:	16.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Smart.Common;

// ReSharper disable CheckNamespace

namespace Smart.Documents.Fields.LookupFieldWithPicker
// ReSharper restore CheckNamespace
{
	public class LookupFieldWithPickerEntityEditor : EntityEditorWithPicker
	{
		protected override bool DefaultPlaceButtonsUnderEntityEditor
		{
			get { return MultiSelect; }
		}

		protected override int DefaultRows
		{
			get
			{
				return
					MultiSelect
						? new LookupFieldWithPickerPropertyBag(CustomProperty).EntityEditorRows
						: base.DefaultRows;
			}
		}

		public PickerEntity GetEntityById(int id)
		{
			PickerEntity entity = null;

			if (id > 0)
			{
				var propertyBag = new LookupFieldWithPickerPropertyBag(CustomProperty);

				using (var web = SPContext.Current.Site.OpenWeb(propertyBag.WebId))
				{
					var list = web.Lists[propertyBag.ListId];

					var item = list.GetItem(id);

					if (item != null)
					{
						entity = GetEntity(item);
					}

					#region Old code

					/*
					var queryById = new SPQuery
										{
											RowLimit = 1,
											ViewAttributes = "Scope=\"Recursive\"",
											Query = string.Format("<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Integer\">{0}</Value></Eq></Where>", id)
										};

					var items = list.GetItems(queryById);

					if (items.Count > 0)
					{
						entity = GetEntity(items[0]);
					}
					 */

					#endregion
				}
			}

			return entity;
		}

		public override PickerEntity ValidateEntity(PickerEntity needsValidation)
		{
			var entity = needsValidation;

			if (!string.IsNullOrEmpty(needsValidation.Key))
			{
				var propertyBag = new LookupFieldWithPickerPropertyBag(CustomProperty);

				using (var web = SPContext.Current.Site.OpenWeb(propertyBag.WebId))
				{
					var list = web.Lists[propertyBag.ListId];

					var field =
						needsValidation.Key == needsValidation.DisplayText
							? list.Fields[propertyBag.FieldId]
							: list.Fields[SPBuiltInFieldId.ID];

					var valueType = field.TypeAsString;

					if (field.Type == SPFieldType.Calculated)
					{
						valueType = "Text";
					}

					var queryString =
						propertyBag.SearchQuery.IsNullOrEmpty() || !AllowTypeIn
							? string.Format(
								"<Where><Eq><FieldRef Name=\"{0}\"/><Value Type=\"{1}\">{2}</Value></Eq></Where>",
								field.InternalName, valueType, needsValidation.Key)
							: string.Format(
								"<Where><And><Eq><FieldRef Name=\"{0}\"/><Value Type=\"{1}\">{2}</Value></Eq>{3}</And></Where>",
								field.InternalName, valueType, needsValidation.Key, propertyBag.SearchQuery);

					var items = SPH.GetFilteredItems(list, queryString, 2, null);

					if (items.Count == 1)
					{
						entity = GetEntity(items[0]);
					}
				}
			}

			return entity;
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			PickerDialogType = typeof(LookupFieldWithPickerDialog);
		}

		protected override void OnPreRender(EventArgs e)
		{
			if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(EntityEditorWithPicker), "__Dialog__" + ClientID))
				ScriptManager.RegisterClientScriptBlock(
					this,
					typeof(EntityEditorWithPicker),
					"__Dialog__" + ClientID,
					"\r\n                    <script type=\"text/javascript\">\r\n                    // <![CDATA[\r\n                    " + PickerActivateScript() +
					"\r\n                    // ]]>\r\n                    </script>",
					false);

			base.OnPreRender(e);
		}

		protected virtual string PickerActivateScript()
		{
			var script = PickerDialog.PickerActivateScript(this, SPControl.GetContextWeb(Context).ServerRelativeUrl, DialogTitle, DialogImage);

			var idx = script.IndexOf("var sDialogUrl = '", StringComparison.OrdinalIgnoreCase);

			if (idx < 0)
				return script;

			var insertIdx = script.IndexOf("\r\n", idx, StringComparison.OrdinalIgnoreCase) + 2;

			if (insertIdx < 2)
				return script;

			var propertyBag = new LookupFieldWithPickerPropertyBag(CustomProperty);

			return
				script.Insert(insertIdx,
							  "                        if (LookupFieldWithPickerBeforeDialogCallback != undefined) sDialogUrl = LookupFieldWithPickerBeforeDialogCallback('" + ClientID + "', '" +
							  propertyBag.FieldName + "', sDialogUrl);\r\n");
		}

		protected override PickerEntity[] ResolveErrorBySearch(string unresolvedText)
		{
			var entities = new List<PickerEntity>();
			var propertyBag = new LookupFieldWithPickerPropertyBag(CustomProperty);

			using (var web = SPContext.Current.Site.OpenWeb(propertyBag.WebId))
			{
				var list = web.Lists[propertyBag.ListId];
				var field = list.Fields[propertyBag.FieldId];
				var valueType = field.TypeAsString;

				if (field.Type == SPFieldType.Calculated)
				{
					valueType = "Text";
				}

				var query =
					string.IsNullOrEmpty(propertyBag.SearchQuery)
						? string.Format(
							"<Where><Contains><FieldRef ID=\"{0}\"/><Value Type=\"{1}\">{2}</Value></Contains></Where>",
							propertyBag.FieldId, valueType, unresolvedText)
						: string.Format(
							"<Where><And><Contains><FieldRef ID=\"{0}\"/><Value Type=\"{1}\">{2}</Value></Contains>{3}</And></Where>",
							propertyBag.FieldId, valueType, unresolvedText, propertyBag.SearchQuery);

				var items = SPH.GetFilteredItems(list, query, 25, null);

				entities.AddRange(items.OfType<SPListItem>().Select(item => GetEntity(item)));
			}

			return entities.ToArray();
		}

		private PickerEntity GetEntity(SPListItem item)
		{
			var propertyBag = new LookupFieldWithPickerPropertyBag(CustomProperty);

			var entity = new PickerEntity();

			string displayValue = null;

			try
			{
				displayValue = item[propertyBag.FieldId].ToString();
			}
			catch
			{
				//field has been deleted
			}

			if (displayValue != null
				&& item.Fields[propertyBag.FieldId].Type == SPFieldType.Calculated
				&& item[propertyBag.FieldId] != null
				&& item[propertyBag.FieldId].ToString().Contains("#"))
			{
				entity.DisplayText = displayValue.Split('#')[1];
			}
			else
			{
				entity.DisplayText = displayValue ?? "";
			}

			entity.Key = item.ID.ToString();
			entity.Description = entity.DisplayText;
			entity.IsResolved = true;

			return entity;
		}
	}
}